import os
import json
import time
import hmac
import hashlib
import base64
import urllib.parse
import requests
from datetime import datetime

class DeviceCommandSender:
    def __init__(self):
        # 直接硬编码配置信息（避免环境变量问题）
        self.access_key_id = "LTAI5tLaEL25ZmTmQDsLgXmp"
        self.access_key_secret = "4okDqudOGjvgngiCzzf5UQqQSZ1AbV"
        self.region_id = "cn-shanghai"
        self.iot_instance_id = "iot-06z00i4wu873xdh"
        self.endpoint = f"https://iot.{self.region_id}.aliyuncs.com"
    
    def _sign_request(self, params):
        """生成阿里云API签名"""
        # 1. 参数排序
        sorted_params = sorted(params.items())
        
        # 2. 构造规范化字符串（特别注意Items参数的编码）
        canonicalized_query_string = "&".join([
            f"{k}={urllib.parse.quote(str(v), safe='')}" for k, v in sorted_params
        ])
        
        # 3. 构造签名字符串  
        string_to_sign = f"POST&%2F&{urllib.parse.quote(canonicalized_query_string, safe='')}"
        
        # 4. 计算签名
        key = self.access_key_secret + "&"
        signature = hmac.new(key.encode("utf-8"), string_to_sign.encode("utf-8"), hashlib.sha1).digest()
        return base64.b64encode(signature).decode("utf-8")
    
    def send_bed_command(self, device_name, product_key, angle, speed_level):
        """发送床板控制指令"""
        try:
            # 参数验证
            if not 0 <= angle <= 90:
                return False, "角度必须在0-90度之间"
            if speed_level not in [1, 2, 3]:
                return False, "速度级别无效，必须是1(慢)、2(正常)或3(快)"
            
            print(f"📡 发送床板控制指令: 设备={device_name}, 角度={angle}°, 速度={speed_level}")
            
            # 构造指令
            items = {
                "servoangle": angle,
                "servospeed": speed_level
            }
            
            # 构造请求参数
            params = {
                "Action": "SetDeviceProperty",
                "IotInstanceId": self.iot_instance_id,
                "ProductKey": product_key,
                "DeviceName": device_name,
                "Items": json.dumps(items),
                "Format": "JSON",
                "Version": "2018-01-20",
                "AccessKeyId": self.access_key_id,
                "SignatureMethod": "HMAC-SHA1",
                "Timestamp": datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),
                "SignatureVersion": "1.0",
                "SignatureNonce": str(int(time.time() * 1000))
            }
            
            # 生成签名
            params["Signature"] = self._sign_request(params)
            
            print(f"🔐 请求参数: {params}")
            
            # 发送请求
            response = requests.post(
                self.endpoint,
                params=params,
                timeout=10
            )
            
            print(f"📊 响应状态: {response.status_code}")
            
            if response.status_code == 200:
                data = response.json()
                print(f"📄 响应数据: {data}")
                
                if data.get("Success"):
                    return True, "指令下发成功"
                else:
                    error_msg = data.get('ErrorMessage', 'Unknown error')
                    return False, f"指令下发失败: {error_msg}"
            else:
                return False, f"HTTP请求失败: {response.status_code} - {response.text}"
                
        except Exception as e:
            print(f"❌ 指令下发错误: {e}")
            return False, f"指令下发错误: {str(e)}"

# 全局指令发送器
command_sender = DeviceCommandSender()
